package com.hejing.初识泛型;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

/**
 * ClassName: EmployeeTest
 * Package: com.hejing.初识泛型
 * Description:
 *
 * @Author: HeJing
 * @Create: 2023-05-21 19:16
 * @Version: 1.0
 */
public class EmployeeTest {

    /**
     * 需求1: 使用Employee实现Comparable接口，按照name排序
     * 自然排序
     */
    @Test
    public void test01(){

        TreeSet<Employee> set = new TreeSet<>();
        Employee e1 = new Employee("HaiMeimei", 19, new MyDate(1999, 10, 9));
        Employee e2 = new Employee("LiLei", 18, new MyDate(2000, 12, 10));
        Employee e3 = new Employee("LeiHua", 19, new MyDate(1999, 2, 8));
        Employee e4 = new Employee("Luffy", 20, new MyDate(1998, 5, 1));
        Employee e5 = new Employee("MingGe", 29, new MyDate(1989, 11, 9));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        // 遍历:
        Iterator<Employee> iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    /**
     * 需求2: 创建TreeSet时传入Comparator对象，按照生日的先后顺序排序
     * 定制排序
     */
    @Test
    public void test02(){

        Comparator<Employee> comparator = new Comparator<Employee>(){
            @Override
            public int compare(Employee o1, Employee o2) {
                // 错误写法，思考为什么
                // return o1.getBirthday().toString().compareTo(o2.getBirthday().toString());

                // 正确写法
                int yearDistance = o1.getBirthday().getYear() - o2.getBirthday().getYear();
                if(yearDistance != 0) return yearDistance;

                int monthDistance = o1.getBirthday().getMonth() - o2.getBirthday().getMonth();
                if(monthDistance != 0) return monthDistance;

                return o1.getBirthday().getDay() - o2.getBirthday().getDay();
            }
        };

        TreeSet<Employee> set = new TreeSet<>(comparator);  // 定制排序

        Employee e1 = new Employee("HaiMeimei", 19, new MyDate(1999, 10, 9));
        Employee e2 = new Employee("LiLei", 18, new MyDate(2000, 12, 10));
        Employee e3 = new Employee("LeiHua", 19, new MyDate(1999, 2, 8));
        Employee e4 = new Employee("Luffy", 20, new MyDate(1998, 5, 1));
        Employee e5 = new Employee("MingGe", 29, new MyDate(1989, 11, 9));

        set.add(e1);
        set.add(e2);
        set.add(e3);
        set.add(e4);
        set.add(e5);

        // 遍历:
        Iterator<Employee> iterator = set.iterator();
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }

    }
}





















